package com.dl7.playerdemo;

import com.bumptech.glide.Glide;
import com.dl7.player.media.IjkPlayerView;
import com.dl7.player.utils.SoftInputUtils;
import com.dl7.playerdemo.utils.ScreenUtils;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.utils.Rect;
import ohos.agp.window.dialog.ToastDialog;
import ohos.agp.window.service.Window;
import ohos.agp.window.service.WindowManager;
import ohos.global.configuration.Configuration;
import ohos.multimodalinput.event.KeyEvent;
import ohos.multimodalinput.event.TouchEvent;
import tv.danmaku.ijk.utils.TextUtils;

import java.io.IOException;

public class IjkPlayerActivity extends Ability {

//    private static final String VIDEO_URL = "http://flv2.bn.netease.com/videolib3/1611/28/GbgsL3639/SD/movie_index.m3u8";
//    private static final String VIDEO_HD_URL = "http://flv2.bn.netease.com/videolib3/1611/28/GbgsL3639/HD/movie_index.m3u8";
//    private static final String IMAGE_URL = "http://vimg2.ws.126.net/image/snapshot/2016/11/I/M/VC62HMUIM.jpg";

    private static final String VIDEO_URL = "https://newcntv.qcloudcdn.com/asp/hls/450/0303000a/3/default/84f142fa588d499d91ef249a01592d95/450.m3u8";
    private static final String VIDEO_HD_URL = "https://newcntv.qcloudcdn.com/asp/hls/450/0303000a/3/default/84f142fa588d499d91ef249a01592d95/450.m3u8";
    private static final String IMAGE_URL = "https://newcntv.qcloudcdn.com/asp/hls/450/0303000a/3/default/84f142fa588d499d91ef249a01592d95/450.m3u8";

    //TODO 2021/8/4
//    Toolbar mToolbar;
    private IjkPlayerView mPlayerView;
    private Component mEtLayout;
    private TextField mEditText;
    private Button mIvSend;
    private Image mImageBack;
    private boolean mIsFocus;
    private DirectionalLayout parentLayout;
    private DirectionalLayout titleBarLayout;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_activity_ijk_player);
        //TODO 2021/8/4
//        mToolbar = (Toolbar) findViewById(R.id.toolbar);
//        setSupportActionBar(mToolbar);
//        mToolbar.setTitle("Video Player");
//        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        WindowManager.getInstance().getTopWindow().get().setTransparent(true);
        Window topWindow = WindowManager.getInstance().getTopWindow().get();
        WindowManager.LayoutConfig layoutConfig = new WindowManager.LayoutConfig();
        layoutConfig.title = "Video Player";
        topWindow.setLayoutConfig(layoutConfig);
        parentLayout = (DirectionalLayout) findComponentById(ResourceTable.Id_parent);
        titleBarLayout = (DirectionalLayout) findComponentById(ResourceTable.Id_slice_video_titleBar);
        mImageBack = (Image) findComponentById(ResourceTable.Id_ijkPlayer_back);
        mPlayerView = (IjkPlayerView) findComponentById(ResourceTable.Id_ijk_player_view);
        mEtLayout = findComponentById(ResourceTable.Id_ijk_ll_layout);
        mEditText = (TextField) findComponentById(ResourceTable.Id_ijk_et_content);
        mIvSend = (Button) findComponentById(ResourceTable.Id_ijk_btn_send);
        Glide.with(this).load(IMAGE_URL).fitCenter().into(mPlayerView.mPlayerThumb);
        mPlayerView.init()
                .setTitle("这是个跑马灯TextView，标题要足够长才会跑。-(゜ -゜)つロ 乾杯~")
                .setSkipTip(1184 * 60 * 1)
                .enableDanmaku()
                .setVideoSource(null, VIDEO_URL, VIDEO_HD_URL, null, null)
                .setMediaQuality(IjkPlayerView.MEDIA_QUALITY_HIGH);
        mPlayerView.initDamukuView("resources/rawfile/bili.xml");

        mImageBack.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                terminateAbility();
            }
        });

        mIvSend.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
//                屏蔽弹幕功能
//                mPlayerView.sendDanmaku(mEditText.getText().toString(), false);
                if (TextUtils.isEmpty(mEditText.getText().toString())) {
                    new ToastDialog(IjkPlayerActivity.this)
                            .setText("内容为空")
                            .show();
                } else {
                    mPlayerView.addDanmaku(mEditText.getText(), true);
                }
                mEditText.setText("");
                _closeSoftInput();
            }
        });
        mEditText.setFocusChangedListener(new Component.FocusChangedListener() {
            @Override
            public void onFocusChange(Component component, boolean isFocus) {
                if (isFocus) {
                    mPlayerView.editVideo();
                }
                mIsFocus = isFocus;
            }
        });

        mPlayerView.getComponentTreeObserver().addWindowBoundListener(new ComponentTreeObserver.WindowBoundListener() {
            @Override
            public void onWindowBound() {
                playerHeight = mPlayerView.getHeight();
                playerWidth = mPlayerView.getWidth();
            }

            @Override
            public void onWindowUnbound() {

            }
        });
    }

    @Override
    protected void onActive() {
        super.onActive();
        mPlayerView.onResume();
    }

    @Override
    protected void onInactive() {
        super.onInactive();
        mPlayerView.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mPlayerView.onDestroy();
    }


    int playerWidth;
    int playerHeight;

    @Override
    public void onConfigurationUpdated(Configuration configuration) {
        //获取当前屏幕对应的高度和宽度
        int screenWidth = ScreenUtils.getScreenWidth(this);
        int screenHeight = ScreenUtils.getScreenHeight(this);
        super.onConfigurationUpdated(configuration);
        if (configuration.direction == Configuration.DIRECTION_HORIZONTAL) {
            mPlayerView.setLayoutConfig(new StackLayout.LayoutConfig(screenWidth, screenHeight));
            titleBarLayout.setVisibility(Component.HIDE);
        } else {
            mPlayerView.setLayoutConfig(new StackLayout.LayoutConfig(screenWidth, 600));
            titleBarLayout.setVisibility(Component.VISIBLE);
        }

        mPlayerView.configurationChanged(configuration);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (mPlayerView.handleVolumeKey(keyCode)) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        if (mPlayerView.onBackPressed()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected boolean onTouchEvent(TouchEvent event) {
        Component component = getCurrentFocus();
        if (_isHideSoftInput(component, (int) event.getPointerPosition(event.getIndex()).getX(),
                (int) event.getPointerPosition(event.getIndex()).getY())) {
            _closeSoftInput();
            return true;
        }
        return super.onTouchEvent(event);
    }

    private void _closeSoftInput() {
        mEditText.clearFocus();
        SoftInputUtils.closeSoftInput(IjkPlayerActivity.this);
        mPlayerView.recoverFromEditVideo();
    }

    private boolean _isHideSoftInput(Component view, int x, int y) {
        if (view == null || !(view instanceof TextField) || !mIsFocus) {
            return false;
        }
        return x < mEtLayout.getLeft()
                || x > mEtLayout.getRight()
                || y < mEtLayout.getTop();
    }
}
